package com.github.vortexdev.yachtclub.util.db;

import java.util.Map;

/**
 * @author Sergey Parakhin (sergey.parahin@gmail.com)
 */
public class QueryBuilder {

    private StringBuilder query;
    private Object[] params;

    public QueryBuilder(String query) {
        this.query = new StringBuilder(query);
        this.params = new Object[0];
    }

    public QueryBuilder(String query, Object[] params) {
        this.query = new StringBuilder(query);
        this.params = params.clone();
    }

    public QueryBuilder filter(Map<String, Object> criteria) {
        if (!criteria.isEmpty()) {
            query.append(" WHERE ");
            int count = params.length;
            int colsCount = 0;
            increaseParamsArraySize(criteria.size());
            for (Map.Entry<String, Object> pair : criteria.entrySet()) {
                query.append(pair.getKey()).append(" LIKE ").append("?");
                params[count++] = pair.getValue() + "%";
                if (++colsCount != criteria.size())
                    query.append(" AND ");
            }
        }
        return this;
    }

    public QueryBuilder orderBy(Sort sort) {
        query.append(" ORDER BY ").append(sort.orderCol)
                .append(" ").append(sort.orderType);
        return this;
    }

    public QueryBuilder page(Page page) {
        query.append(" LIMIT ?, ? ");
        int last = params.length;
        increaseParamsArraySize(2);
        params[last] = page.pageSize * (page.page - 1);
        params[last + 1] = page.pageSize;
        return this;
    }

    public String getQuery() {
        return query.toString();
    }

    public Object[] getParams() {
        return params;
    }

    private void increaseParamsArraySize(int increaseSize) {
        Object[] newArray = new Object[params.length + increaseSize];
        System.arraycopy(params, 0, newArray, 0, params.length);
        this.params = newArray;
    }

}
